package net.zdsoft.wpchat.support.entity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 用户拥有大类目录权限
 *
 * @author xuan
 */
public class UserCatalog {
    private static Logger logger = LoggerFactory.getLogger(UserCatalog.class);

    private AuthCatalog catalog = null;
    private final HashMap<String, UserModule> userModuleMap = new HashMap<String, UserModule>();
    private final List<UserModule> userModuleList = new ArrayList<UserModule>();

    public UserCatalog(AuthCatalog catalog) {
        this.catalog = catalog;
    }

    public AuthCatalog getCatalog() {
        return catalog;
    }

    public UserModule putUserModule(UserModule userModule) {
        String moduleId = userModule.getModule().getId();
        UserModule _userModule = userModuleMap.get(moduleId);
        if (_userModule == null) {
            logger.debug("Put module[" + userModule.getModule().getName() + "]");
            userModule.setUserCatalog(this);
            userModuleMap.put(moduleId, userModule);
            userModuleList.add(userModule);
            return userModule;
        }

        return _userModule;
    }

    public UserModule getFirstModule() {
        return userModuleList.get(0);
    }

    public List<UserModule> getUserModuleList() {
        return userModuleList;
    }

    public void orderModuleByVisibleIndex() {
        Collections.sort(userModuleList, new Comparator<UserModule>() {
            @Override
            public int compare(UserModule o1, UserModule o2) {
                AuthModule module0 = o1.getModule();
                AuthModule module1 = o2.getModule();
                return module0.getDisplayOrder() - module1.getDisplayOrder();
            }
        });
    }

}
